package com.witdata.quartz.job;

import com.alibaba.fastjson2.JSON;
import com.witdata.common.domain.dto.InstanceDto;
import com.witdata.common.exception.GlobalException;
import com.witdata.rabbit.domain.Handle;
import com.witdata.rabbit.producer.InstanceProducer;
import com.witdata.rabbit.service.InstanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class InstanceHeartbeatJob implements Job {
    private final InstanceProducer instanceProducer;
    private final InstanceService instanceService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<InstanceDto> instanceList = instanceService.getInstanceList();
        if (!CollectionUtils.isEmpty(instanceList)) {
            instanceList.forEach(this::checkInstanceHeart);
        }
    }

    @Async("instanceHeartbeatTaskExecutor")
    public void checkInstanceHeart(InstanceDto instanceDto) {
        try {
            String data = instanceProducer.send(instanceDto.getId(), Handle.Heartbeat, null);
            InstanceDto item = JSON.parseObject(data, InstanceDto.class);
            item.setMemoryUsage((int) (item.getUsedMemory() * 100 / item.getTotalMemory()));
            item.setStatus(InstanceDto.Status.Online);
            instanceService.updateInstance(item);
        } catch (GlobalException e) {
            instanceService.updateInstance(
                    InstanceDto.builder()
                            .id(instanceDto.getId())
                            .status(InstanceDto.Status.Offline)
                            .build()
            );
        }
    }
}
